//
//  DocumentViewController.m
//  FMS
//
//  Created by Steven on 10/15/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "DocumentViewController.h"
#import "DetailedItemViewController.h"
#import "DetailedDocumentViewController.h"

@interface DocumentViewController ()

@end

@implementation DocumentViewController
@synthesize parent;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil itemType:(int)_itemType parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        parent = _parent;
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        itemType = _itemType;
    }
    return self;
}

- (void) didSelectPhoto:(AsynImageButton*)sender {
    if (!scrollDocument.isDisplayButtonDelete) {
        if (sender.tag == 0) {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            
            NSMutableDictionary *buildingPermissionDict;
            if (itemType == Building_Type)
                buildingPermissionDict = [userDefaults objectForKey:BUILDING_PERMISSION];
            else
                buildingPermissionDict = [userDefaults objectForKey:FACILITY_PERMISSION];
            
            //Get permission about this tab
            //if has Edit permission is also has Add permission
            NSMutableDictionary *permissionDict = [buildingPermissionDict objectForKey:@"documentAttachment"];
            BOOL isAdd = [[permissionDict objectForKey:@"add"] boolValue];
            if (!isAdd) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }
            
            if (popController != nil) {
                [popController dismissPopoverAnimated:YES];
                popController = nil;
            }
            imagePickerController = [[UIImagePickerController alloc] init];
            NSArray *mediaTypes;
            NSString *requiredMediaType = (NSString *)kUTTypeImage;
            
            mediaTypes = [NSArray arrayWithObject:requiredMediaType];
            imagePickerController.delegate = self;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.mediaTypes = mediaTypes;
            imagePickerController.allowsEditing = YES;
            UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
            popController = popover;
            popController.delegate = self;
            [popController presentPopoverFromRect:sender.frame inView:sender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
            
            imagePickerController = nil;
        }
        else {
            [(DetailedItemViewController*)parent selectDetailedDocument:sender];
        }
    }
}

- (void) deleteItemDocument:(AsynImageButton*)_sender {
    NSLog(@"btn = %@",_sender.dataDict);
    NSError *error;
    [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:[_sender.dataDict objectForKey:@"_id"] error:&error];
    if (!error) {
        [scrollDocument.itemArray removeObject:_sender.dataDict];
        [scrollDocument setupPage];
    }
}

#pragma mark UIImagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //create document to save photo for this item
    NSString *itemId = [((DetailedItemViewController*)parent).itemDetailedDict objectForKey:@"_id"];
    
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *todayStr = [dateFormatter stringFromDate:today];
    
    NSString *imageUrl = [NSString stringWithFormat:@"%@",[info objectForKey:UIImagePickerControllerReferenceURL]];
    
    //create document to save photo for this item
    NSData *fileData;
    NSString *lastChosenMediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([lastChosenMediaType isEqual:(NSString *)kUTTypeImage]) {
        UIImage *chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        fileData = UIImageJPEGRepresentation(chosenImage, 1.0);
    }
    
    //check existed or not?
    if (![CouchBaseLiteLib checkExistedItemByDocument:itemId documentLink:imageUrl]) {
        
        //name for this document by today
        NSString *fileName = todayStr;
        
        NSMutableDictionary *photoDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:todayStr,@"dateUploaded",imageUrl,@"imageUrl",itemId,@"itemId",DocumentAttachment,@"Table",fileName,@"fileName",nil];
        
        NSError *error;
//        [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:photoDict error:&error];
        [[CouchBaseLiteLib sharedCouchBaseLite] createDocumentWithAttachment:photoDict fileData:fileData error:&error];
        if (!error) {
            [documentArray addObject:photoDict];
            
            [self reloadPageView];
            
            [popController dismissPopoverAnimated:YES];
            popController = nil;
        }
    }
    else {
        //duplicate document for this item
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.detail.document-link.duplicate"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
    
    //hide status bar after select image
    [self performSelector:@selector(hideStatusBar) withObject:self afterDelay:1.0];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [popController dismissPopoverAnimated:YES];
    popController = nil;
    
    //hide status bar after select image
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
    else
    {
        // iOS 6
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
}

- (void) hideStatusBar {
    //hide status bar after select image
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
    else
    {
        // iOS 6
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
}

#pragma mark UIPopoverControllerDelegate
#pragma mark UIPopoverControllerDelegate
- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController {
    return YES;
}
- (void) popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
    //hide status bar after select image
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
    else
    {
        // iOS 6
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
}

- (BOOL) prefersStatusBarHidden {
    return YES;
}

- (void) reloadPageView {
    
    scrollDocument.itemArray = documentArray;
    [scrollDocument setupPage];
}

- (void) listDocumentsByItem {
    [documentArray removeAllObjects];
    
    NSMutableDictionary *buttonDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:0],@"buttonType", nil];
    
    documentArray = [CouchBaseLiteLib listDocumentAttachmentByItem:[((DetailedItemViewController*)parent).itemDetailedDict objectForKey:@"_id"]];
    [documentArray insertObject:buttonDict atIndex:0];
    
    scrollDocument.itemArray = documentArray;
    [scrollDocument setupPage];
    
    [myActivityView stopAnimating];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    documentArray = [NSMutableArray arrayWithCapacity:1];
    
    scrollDocument = [[UIScrollDocument alloc] initWithFrame:CGRectMake(20, 20, 874, 624) parent:self];
    [self.view addSubview:scrollDocument];
    
    myActivityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, 25, 25)];
    myActivityView.hidesWhenStopped = YES;
    myActivityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.view addSubview:myActivityView];
    [myActivityView startAnimating];
    
    //list document attachment
//    [self performSelectorInBackground:@selector(listDocumentsByItem) withObject:nil];
    [self performSelector:@selector(listDocumentsByItem) withObject:nil afterDelay:0.5];
}

@end
